package registrar;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AspectJTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;

/**
 * @author wuli
 * @create 2021-12-28 22:32
 */
public class CustomImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    private String expression;

    private String custonPackages;

    public CustomImportBeanDefinitionRegistrar() {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("customimport.properties");
            expression = properties.getProperty("custom.import.registrar.expression");
            custonPackages = properties.getProperty("custom.import.registrar.package");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        List<String> list = null;

        if (importingClassMetadata.hasAnnotation(ComponentScan.class.getName())) {
            Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(ComponentScan.class.getName());
            list = new ArrayList<String>(Arrays.asList((String[]) annotationAttributes.get("basePackages")));
        }

        if (list == null || list.size() == 0) {
            try {
                String basePackage = Class.forName(importingClassMetadata.getClassName()).getPackage().getName();
                list = new ArrayList<String>();
                list.add(basePackage);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        if (!StringUtils.isEmpty(custonPackages)) {
            list.add(custonPackages);
        }

        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
        TypeFilter typeFilter = new AspectJTypeFilter(expression, CustomImportBeanDefinitionRegistrar.class.getClassLoader());
        scanner.addIncludeFilter(typeFilter);
        scanner.scan(list.toArray(new String[list.size()]));
    }
}
